import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as MineCustomerAction from '../actions/mineCustomer'

import WeaRightLeftLayout from './weaCrmRightLeft'
import WeaCrmTab from './weaCrmTab'
import WeaDropdown from './weaCrmDropdown';
import ViewContactLog from './data/ViewContactLog.js'
import ViewContacter from './data/ViewContacter.js'
import ViewLeaveMessage from './data/ViewLeaveMessage.js'
import ViewSellChance from './data/ViewSellChance.js'
import SetTagModal from './data/SetTagModal.js'

// import CustomerContact from './CustomerContact.js'
import CardManage from  './card/cardManage.js'

import { WeaTable } from 'comsRedux'
const WeaTableAction = WeaTable.action;

import {
    WeaTab,
    WeaReqTop,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm,
    WeaSelect ,
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
const { getComponent } = WeaTools;

import {Button,Form,Modal,message,Spin,Rate,Tooltip,Icon,Tabs } from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;
const TabPane = Tabs.TabPane;

import cloneDeep from 'lodash/cloneDeep'
import objectAssign from 'object-assign'
import WeaFormmodeTop from './WeaFormmodeTop'
import PropTypes from 'react-router/lib/PropTypes'
import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class MineCustomer extends React.Component {
    constructor(props) {
		super(props);
		_this = this;
    }
    componentDidMount() {
    	 const {actions} = this.props;
         actions.setNowRouterCmpath('mineCustomer');
         actions.getMyCustomerTags();
         actions.conditionTop();
         actions.getMyCustomerTagsList({type:"crm"});
         actions.doSearch();
         actions.getContactLogs();
         actions.getRemindCount();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if(keyOld!==keyNew) {
            const {actions} = this.props;
            actions.isClearNowPageStatus();

            actions.setNowRouterCmpath('mineCustomer');
            actions.getMyCustomerTags();
            actions.conditionTop();
            actions.getMyCustomerTagsList({type:"crm"});
            actions.doSearch();
            actions.getContactLogs();
            actions.getRemindCount();
        }
    }
    shouldComponentUpdate(nextProps,nextState) {
         return !is(this.props.title,nextProps.title)||
            !is(this.props.dataKey,nextProps.dataKey)||
            !is(this.props.loading,nextProps.loading)||
            !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
            !is(this.props.showSearchAd,nextProps.showSearchAd)||
            !is(this.props.orderFields,nextProps.orderFields)||
            !is(this.props.detailTabKey,nextProps.detailTabKey)||
            !is(this.props.tabDatas,nextProps.tabDatas)||
            !is(this.props.sectorTreeData,nextProps.sectorTreeData)||
            !is(this.props.statusOptions,nextProps.statusOptions)||
            !is(this.props.hrmList,nextProps.hrmList)||
            !is(this.props.viewTypeList,nextProps.viewTypeList)||
            !is(this.props.isShowResource,nextProps.isShowResource)||
            !is(this.props.istorefresh,nextProps.istorefresh)||
            !is(this.props.rightTabKey,nextProps.rightTabKey)||
            !is(this.props.contactLogs,nextProps.contactLogs)||
            !is(this.props.cardloading,nextProps.cardloading)||
            !is(this.props.selectValue,nextProps.selectValue)||
            !is(this.props.contacterCard,nextProps.contacterCard)||
            !is(this.props.leaveMessage,nextProps.leaveMessage)||
            !is(this.props.sellChanceCard,nextProps.sellChanceCard)||
            !is(this.props.tagDatas,nextProps.tagDatas)||
            !is(this.props.showRight,nextProps.showRight)||
            !is(this.props.rightInfos,nextProps.rightInfos)||
            !is(this.props.remindCount,nextProps.remindCount)
  
    }
    componentWillUnmount(){

    }
    render() {
        const {loading,actions,dataKey,title,comsWeaTable,tabDatas,detailTabKey,rightTabData,rightTabKey,contactLogs,cardloading,istorefresh} = this.props;
        const {selectValue,contacterCard,leaveMessage,sellChanceCard,tagDatas,showRight,rightInfos,remindCount} = this.props;
        const name = dataKey ? dataKey.split('_')[0] : 'init';
        const loadingTable = comsWeaTable.get(name).toJS().loading;
        return (
            <div>
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                     <WeaFormmodeTop
                        title={title}
                        loading={loading || loadingTable}
                        icon={<i className='icon-coms-crm' />}
                        tabDatas={tabDatas.toJS()}
                        selectedKey={detailTabKey}
                        onChange={this.changeData.bind(this)}
                        iconBgcolor='#96358a'
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.getRightMenu()}
                    >
                         <WeaRightLeftLayout  defaultShowLeft={false} leftCom={this.getCustomerTable()} >
                         {
                            !showRight &&  
                            <div className="crm-right-tab">
                                <div className="sellchancemain-right-top">
                                    <WeaSelect 
                                    value={selectValue}   
                                    options={[{key: "1", selected: true, showname:"近一月"},
                                            {key: "2", selected: false, showname: "近三月"},
                                            {key: "3", selected: false, showname: "近半年"},
                                            {key: "4", selected: false, showname: "近一年"},
                                            {key: "0", selected: false, showname: "全部"}]} 
                                    onChange={this.dateSelectChange.bind(this)}
                                    />
                                </div>
                                <WeaTab
                                    selectedKey={rightTabKey}
                                    datas={rightTabData.toJS()}
                                    keyParam='key'
                                    onChange={this.changeRightTab.bind(this)} 
                                />
                                    {
                                        rightTabKey =="1" && 
                                        <div className="contact-logs-container">
                                            <Spin spinning={cardloading} >
                                                <ViewContactLog  data={contactLogs} />
                                            </Spin>
                                        </div>
                                    }
                                    { 
                                    rightTabKey =="2" && 
                                        <div className="contact-logs-container">
                                            <Spin spinning={cardloading} >
                                                <ViewContacter  data={contacterCard} />
                                            </Spin>
                                        </div>
                                    }
                                    {
                                        rightTabKey =="3" && 
                                        <div className="contact-logs-container">
                                            <Spin spinning={cardloading} >
                                                <ViewLeaveMessage  data={leaveMessage} />
                                            </Spin>
                                        </div>
                                    }
                                    { 
                                    rightTabKey =="4" && 
                                    <div className="contact-logs-container">
                                            <Spin spinning={cardloading} >
                                                <ViewSellChance  data={sellChanceCard} />
                                            </Spin>
                                        </div>
                                    }
                            </div>
                         }
                         {
                             showRight && <CardManage  
                                paramsData={{from:"mine",customerId:rightInfos.get('customerId')}} 
                                rightInfos={rightInfos} 
                                type="minecustomer"
                             />
                         }
                        </WeaRightLeftLayout>
                    </WeaFormmodeTop>
                </WeaRightMenu>
                <WeaPopoverHrm  />
                <SetTagModal ref="setTagModal" data={tagDatas.toJS()} actions={actions} type={"crm"}/>
            </div>
        )
    }
    onRightMenuClick(key){
    	 const {actions,comsWeaTable,dataKey} = this.props;
    	if(key == '0'){

    	}
    	if(key == '1'){
    		// actions.batchSubmitClick({checkedKeys:`${selectedRowKeys.toJS()}`})
    	}
    }
    getRightMenu(){
    	let btns = [];   
    	btns.push({
    		icon: <i className='icon-coms-Collection'/>,
    		content:'收藏'
    	});
        btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
        })
    	return btns
    }
     getButtons() {
        const {remindCount} = this.props;
        let btnArr = [];
        btnArr.push(<Tooltip placement="bottom" title={"新建客户"}><span onClick={()=>crmOpenSPA4Single('/main/crm/addCustomer?type=1')}><i className="crm-hover-icon icon-crm-addcustomer" style={{fontSize:"20px"}} /></span></Tooltip>);
        btnArr.push(<Tooltip placement="bottom" title={"客户导入"}><span onClick={()=>crmOpenSPA4Single('/main/crm/addCustomer?type=2')}><i className="crm-hover-icon icon-crm-customerimport" style={{fontSize:"20px"}}/></span></Tooltip>);
        btnArr.push(<Tooltip placement="bottom" title={"客户生日提醒"}><span onClick={()=>crmOpenSPA4Single('/main/crm/birthday')}><i className="crm-hover-icon icon-crm-birthday" style={{fontSize:"20px"}}/></span></Tooltip>);
        btnArr.push(<Tooltip placement="bottom" title={"客户联系提醒"}><span onClick={()=>crmOpenSPA4Single('/main/crm/contact')}><Icon className="crm-hover-icon"  type="notification" style={{fontSize:"16px"}}/><span style={{color:"#2db7f5"}}>{"("+remindCount+")"}</span></span></Tooltip>);
        return btnArr
    }
     changeData(key){
         const {actions,istorefresh} = this.props;
         actions.setMineCustomerTabKey(key,istorefresh);
    }
    changeRightTab(key){
        const {actions} = this.props;
         actions.setRightTabKey(key);
    }
    dateSelectChange(val){
        const {actions,rightTabKey} = this.props;
        actions.saveSelectValue(val);
        if(rightTabKey == "1"){actions.getContactLogs({datatype:val});}
        if(rightTabKey == "2"){actions.getContacterCard({datatype:val});}
        if(rightTabKey == "3"){actions.getLeaveMessage({datatype:val});}
        if(rightTabKey == "4"){actions.getSellchanceCard({datatype:val});}
    }
     getCustomerTable(){
         const {searchParamsAd,actions,dataKey,showSearchAd,orderFields} = this.props;
         return (
             <div>
                <WeaCrmTab
                    searchType={['base']}
                    selectGroups={this.getSelectGroups()}
                    searchsBaseValue={searchParamsAd.get('name')}
                    onSearch={v=>{actions.doSearch()}}
                    hasDropMenu={true}
                    onSearchChange={v=>{actions.saveOrderFields({...orderFields.toJS(),...{name:{name:'name',value:v}}})}}
                />
                <WeaTable 
                    sessionkey={dataKey}
                    hasOrder={true}
                    needScroll={true}
                    getColumns = {columns=>{ 
                        let newcol = [].concat(columns);
                        if(newcol.length>0){
                            newcol[0].render = (text, record,index) => (<div className="crm-mine-customer-list" onClick={()=>{this.viewCustomerDetail(record.randomFieldId)} }>{text}</div> )
                            newcol[1].render = (text, record,index) => {
                               return  <span dangerouslySetInnerHTML={{__html:record.managerspan}}></span>
                            }
                            newcol[2].render = (text, record,index) => (<span><Rate count={1}  value={text} onChange={text=>{this.focusOnClick(record.important,record.randomFieldId)}} /></span> )
                        }
                        return newcol}}
                />
             </div>
         )
    }
     getSelectGroups(){
        const {hrmList,viewTypeList,statusOptions,isShowResource,sectorTreeData,istorefresh,tagDatas}  =this.props;
        const {actions,dataKey, comsWeaTable,} = this.props;
        let statusOptions1 = statusOptions.toJS();
             statusOptions1.unshift({"id":"","name":"全部状态"});
         let sectorTreeData1 =sectorTreeData.toJS();
             sectorTreeData1.unshift({"id": "","isLeaf": true,"name": "全部行业","getLeafApi": ""});
        
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
        const selectedRowKeys = tableNow.get('selectedRowKeys');
        let that = this;
        const tabBtns = (function(){
            if(isShowResource){
                return  <Tabs defaultActiveKey="">
                <TabPane tab={
                    <WeaDropdown 
                        keyValue="resourceid" 
                        defaultValue={hrmList.toJS()[0].name} 
                        type="tree" 
                        datas={hrmList.toJS()} 
                        hrmListChange={that.onHrmListChange}
                        onChange={that.selectChange.bind(that)} 
                    />   
                } key="1"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="viewtype" defaultValue={viewTypeList.toJS()[0].name} type="select" datas={viewTypeList.toJS()} onChange={that.selectChange.bind(that)}/>
                } key="2"></TabPane> 
                <TabPane tab={
                    <WeaDropdown keyValue="status" defaultValue="全部状态" type="select" datas={statusOptions1} onChange={that.selectChange.bind(that)}/>
                 } key="3"></TabPane>
                <TabPane tab={
                    <WeaDropdown keyValue="sector" 
                        defaultValue={sectorTreeData1[0].name} 
                        type="tree" 
                        datas={sectorTreeData1} 
                        onChange={that.selectChange.bind(that)} 
                        hrmListChange={that.industryChange}
                    />
                } key="4"></TabPane>
                <TabPane tab={
                    <WeaDropdown 
                        defaultValue="标签" 
                        type="tag" 
                        datas={tagDatas.toJS()} 
                        selectKeys={`${selectedRowKeys.toJS()}`} 
                        markTagsTo={that.markTagsTo.bind(that)}
                        markToCustomTag={that.markToCustomTag.bind(that)}
                        setting={that.setting.bind(that)}
                    />
                } key="5"></TabPane>
            </Tabs>
            }else{
                return <Tabs defaultActiveKey="">
                    <TabPane tab={
                        <WeaDropdown keyValue="status" defaultValue="全部状态" type="select" datas={statusOptions1} onChange={that.selectChange.bind(that)}/>
                    } key="3"></TabPane>
                    <TabPane tab={
                        <WeaDropdown keyValue="sector" 
                            defaultValue={sectorTreeData1[0].name} 
                            type="tree" 
                            datas={sectorTreeData1} 
                            onChange={that.selectChange.bind(that)} 
                            hrmListChange={that.industryChange}
                        />
                    } key="4"></TabPane>
                    <TabPane tab={
                        <WeaDropdown 
                            defaultValue="标签" 
                            type="tag" 
                            datas={tagDatas.toJS()} 
                            selectKeys={`${selectedRowKeys.toJS()}`} 
                            markTagsTo={that.markTagsTo.bind(that)}
                            markToCustomTag={that.markToCustomTag.bind(that)}
                            setting={that.setting.bind(that)}
                        />
                    } key="5"></TabPane>
                </Tabs>
            }
        })();
        return tabBtns
    }
    onHrmListChange = (arr)=>{
        const {actions} = this.props;
        actions.saveHrmList(arr);
    }
    industryChange=(arr)=>{
        const {actions} = this.props;
        actions.saveIndustry(arr);
    }
    viewCustomerDetail=(id)=>{
        
        const {actions} = this.props;
        actions.viewCustomerDetail(id);
    }
     selectChange(obj){
        const {actions,orderFields} = this.props;
        actions.saveOrderFields({...orderFields.toJS(),...obj});
        actions.doSearch();
        // actions.getContactLogs();
        actions.saveSelectValue("1");
        actions.setRightTabKey("1");
    }

    focusOnClick=(num,id)=>{  //点击星星
        let flag =  1;
        if(num=="1"){flag = 0}
        this.markTagsTo(flag,id);
    }
    markTagsTo(i,key){   // 重要  取消重要
        const {actions} = this.props;
        actions.isMarkToImportant({relatedIds:key,important:i,type:"crm"});
        actions.doSearch();
    }
    markToCustomTag(lablestr,selectkey,type){   //应用  取消某标签
         const {actions} = this.props;
        actions.markToCustomTagType({relatedIds:selectkey,labelIds:lablestr,operationType:type,type:"crm"});
    }
    setting(){
        this.refs.setTagModal.visible = true
    }
    getSearchs() {    //右边列表高级搜索
		let group = [];
		return group
    }
}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

MineCustomer = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(MineCustomer);

MineCustomer = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOrderFields({...props.orderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.orderFields.toJS();
  	}
})(MineCustomer);


function mapStateToProps(state) {
	const {mineCustomer,comsWeaTable} = state;
    return  {
        loading: mineCustomer.get('loading'),
        title: mineCustomer.get('title'),
        dataKey:mineCustomer.get('dataKey'),
        detailTabKey:mineCustomer.get('detailTabKey'),
        showSearchAd:mineCustomer.get('showSearchAd'),
        orderFields: mineCustomer.get('orderFields'),
        tabDatas:mineCustomer.get('tabDatas'),
        sectorTreeData:mineCustomer.get('sectorTreeData'),
        statusOptions:mineCustomer.get('statusOptions'),
        hrmList:mineCustomer.get('hrmList'),
        viewTypeList:mineCustomer.get('viewTypeList'),
        isShowResource:mineCustomer.get('isShowResource'),
        searchParamsAd:mineCustomer.get('searchParamsAd'),
        istorefresh:mineCustomer.get('istorefresh'),
        rightTabData:mineCustomer.get('rightTabData'),
        rightTabKey:mineCustomer.get('rightTabKey'),
        contactLogs:mineCustomer.get('contactLogs'),
        cardloading:mineCustomer.get('cardloading'),
        selectValue:mineCustomer.get('selectValue'),
        contacterCard:mineCustomer.get('contacterCard'),
        leaveMessage:mineCustomer.get('leaveMessage'),
        sellChanceCard:mineCustomer.get('sellChanceCard'),
        tagDatas:mineCustomer.get('tagDatas'),
        rightInfos:mineCustomer.get('rightInfos'),
        showRight:mineCustomer.get('showRight'),
        remindCount:mineCustomer.get('remindCount'),
         //table
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...MineCustomerAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(MineCustomer);
